﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FourPartHarmony3 {
    class ChordPlayer {
        private const int DEFAULT_VELOCITY = 48;

        MidiOutput mMidiOutput;
        int mVelocity = DEFAULT_VELOCITY;
        private List<int> mListPlayNotes = new List<int>();

        public ChordPlayer(MidiOutput mo) {
            mMidiOutput = mo;
        }

        /// <param name="velocity">0～127</param>
        public void SetVelocity(int velocity) {
            mVelocity = velocity;
        }

        public int GetVelocity() {
            return mVelocity;
        }

        public void Play(Chord c) {
            Stop();

            PlayPart(c, Part.Bas);
            PlayPart(c, Part.Ten);
            PlayPart(c, Part.Alt);
            PlayPart(c, Part.Sop);
        }

        private void PlayPart(Chord c, Part part) {
            if (c.GetPitch(part).LetterName.Is(LN.NA)) {
                return;
            }

            int note = PitchToNote(c.GetPitch(part));
            mListPlayNotes.Add(note);
            mMidiOutput.SendShortMsg(MidiOutput.COMMAND_NOTE_ON, 0, note, mVelocity);
        }

        private static int PitchToNote(Pitch pitch) {
            return pitch.LetterName.ToFreqIndex() + 12 * (pitch.Octave + 1);
        }

        public void Stop() {
            foreach (var note in mListPlayNotes) {
                mMidiOutput.SendShortMsg(MidiOutput.COMMAND_NOTE_OFF, 0, note, 0);
            }
            mListPlayNotes.Clear();
        }

    }
}
